﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace SHKF.B2C.JuShuiTan.Network
{
    public class TaoBaoClient 
    {  
        private static string url = "http://a1q40taq0j.api.taobao.com/router/qm";
 
        public string GetOrderList()
        {
            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("page_index", "1");
            param.Add("page_size", "25");

            string result = Post("jushuitan.order.list.query", "", param); 
            return result;
        }
 
        private string Post(string method, string session, IDictionary<string, string> param) 
        {
            #region -----API系统参数---- 

            param.Add("target_app_key", "23060081");
            param.Add("customer_id", "jlxixinyiyao");

            param.Add("app_key", "32305619"); 
            param.Add("method", method); 
            param.Add("session", session); 
            param.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); 
            param.Add("format", "json"); 
            param.Add("v", "2.0"); 
            param.Add("sign_method", "md5"); 
            param.Add("sign", CreateSign(param, "007274989b16e8151e548b0f41d5c3db")); 

            #endregion 

            string result = string.Empty; 

            #region ---- 完成 HTTP POST 请求----
             
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); 
            req.Method = "POST"; 
            req.KeepAlive = true; 
            req.Timeout = 300000; 
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

            byte[] postData = Encoding.UTF8.GetBytes(Sort(param)); 
            Stream reqStream = req.GetRequestStream(); 
            reqStream.Write(postData, 0, postData.Length); 
            reqStream.Close(); 
            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse(); 
            Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet); 
            Stream stream = null; 
            StreamReader reader = null; 
            stream = rsp.GetResponseStream(); 
            reader = new StreamReader(stream, encoding); 
            result = reader.ReadToEnd(); 
            if (reader != null) reader.Close(); 
            if (stream != null) stream.Close(); 
            if (rsp != null) rsp.Close();

            #endregion

            string json = Regex.Replace(result, @"[\x00-\x08\x0b-\x0c\x0e-\x1f]", "");
            return json;

        }

        private string Sort(IDictionary<string, string> parameters)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;
            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            { 
                string name = dem.Current.Key;
                string value = dem.Current.Value;

                // 忽略参数名或参数值为空的参数 
                if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value)) 
                { 
                    if (hasParam) 
                    { 
                        postData.Append("&"); 
                    } 
                    postData.Append(name); 
                    postData.Append("="); 
                    postData.Append(Uri.EscapeDataString(value)); 
                    hasParam = true; 
                } 
            } 

            return postData.ToString();

        }

        private string CreateSign(IDictionary<string, string> parameters, string secret)
        {
            parameters.Remove("sign");

            IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
            IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();
            StringBuilder query = new StringBuilder(secret);

            while (dem.MoveNext())
            {
                string key = dem.Current.Key;

                string value = dem.Current.Value;
                if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                {
                    query.Append(key).Append(value);
                }
            }

            query.Append(secret);
            MD5 md5 = MD5.Create();
            byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()));

            StringBuilder result = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                string hex = bytes[i].ToString("X");
                if (hex.Length == 1)
                {
                    result.Append("0");
                }
                result.Append(hex);
            }
            return result.ToString();

        }

    }

}
 